﻿using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Prism.Events;
using WPFNote.Utilities.Common;
using WPFNote.Utilities.Extensions;
using WPFNote.ViewModels;

namespace WPFNote.Views
{
    public partial class MainWindow : Window
    {
        private readonly IDialogHostService dialogHostService;
        public MainWindow(IEventAggregator aggregator, IDialogHostService dialogHostService)
        {
            InitializeComponent();
            
            //注册提示消息
            aggregator.ResgiterMessage(arg =>
            {
                Snackbar.MessageQueue?.Enqueue(arg.Message);
            }, "MainWindow");
            
            //注册等待消息窗口
            aggregator.Resgiter(arg =>
            {
                DialogHost.IsOpen = arg.IsOpen;
                if (DialogHost.IsOpen)
                    DialogHost.DialogContent = new Progress();
            });

            BtnMin.Click += (s, e) => { this.WindowState = WindowState.Minimized; };
            BtnMax.Click += (s, e) =>
            {
                this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
            };
            BtnClose.Click += async (s, e) =>
            {
                await CloseWindow();
            };
            
            this.dialogHostService = dialogHostService;
        }
        /// <summary>
        /// 排序文本框输入，只能限制是数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TbxCategorySort_OnPreviewTextInput(object sender, TextCompositionEventArgs e) {
            var re = new Regex("[^0-9.-]+");
            e.Handled = re.IsMatch(e.Text);
        }

        private async Task CloseWindow()
        {
            var dialogResult = await dialogHostService.Question("温馨提示", "确认是否关闭 ?");
            if (dialogResult.Result != Prism.Services.Dialogs.ButtonResult.OK)
                return;
            if (DataContext is MainWindowViewModel viewModel)
            {
                await viewModel.UploadDataBase();
            }

            Application.Current.Shutdown(); 
        }
    }
}